<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { SystemPostApi } from '#/api/system/post';

import { ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart, isEmpty } from '@vben/utils';

import { ElButton, ElLoading, ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deletePost,
  deletePostList,
  exportPost,
  getPostPage,
} from '#/api/system/post';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

/** 刷新表格 */
function handleRefresh() {
  gridApi.query();
}

/** 导出表格 */
async function handleExport() {
  const data = await exportPost(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: '岗位.xls', source: data });
}

/** 创建岗位 */
function handleCreate() {
  formModalApi.setData(null).open();
}

/** 编辑岗位 */
function handleEdit(row: SystemPostApi.Post) {
  formModalApi.setData(row).open();
}

/** 删除岗位 */
async function handleDelete(row: SystemPostApi.Post) {
  try {
    await ElMessageBox.confirm(
      $t('ui.actionMessage.deleteConfirm', [row.name]),
      $t('common.tips'),
      {
        type: 'warning',
        confirmButtonText: $t('common.confirm'),
        cancelButtonText: $t('common.cancel'),
      },
    );

    const loading = ElLoading.service({
      lock: true,
      text: $t('ui.actionMessage.deleting', [row.name]),
    });

    try {
      await deletePost(row.id!);
      ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
      handleRefresh();
    } finally {
      loading.close();
    }
  } catch {
    // 用户取消删除
  }
}

/** 批量删除岗位 */
async function handleDeleteBatch() {
  await ElMessageBox.confirm(
    $t('ui.actionMessage.deleteBatchConfirm', [$t('system.post.name')]),
    $t('common.tips'),
    {
      confirmButtonText: $t('common.confirm'),
      cancelButtonText: $t('common.cancel'),
      type: 'warning',
    },
  );

  const loading = ElLoading.service({
    lock: true,
    text: $t('ui.actionMessage.deletingBatch', [$t('system.post.name')]),
  });
  try {
    await deletePostList(checkedIds.value);
    checkedIds.value = [];
    ElMessage.success($t('ui.actionMessage.deleteSuccess'));
    handleRefresh();
  } finally {
    loading.close();
  }
}
const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: SystemPostApi.Post[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}
/**
 * 列表配置
 */
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
    // 搜索栏展开折叠按钮是折叠 true 折叠 false 收起
    collapsed: true,
  },
  gridOptions: {
    columns: useGridColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getPostPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      search: true,
      custom: true,
      export: false,
      refresh: true,
      zoom: true,
    },
  } as VxeTableGridOptions<SystemPostApi.Post>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<SystemPostApi.Post>) {
  switch (code) {
    case 'delete': {
      handleDelete(row);
      break;
    }
    case 'edit': {
      handleEdit(row);
      break;
    }
  }
}
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="handleRefresh" />
    <Grid table-title="岗位列表">
      <template #toolbar-tools>
        <ElButton type="primary" @click="handleCreate"> 新建岗位 </ElButton>
        <ElButton type="primary" @click="handleExport"> 导出岗位 </ElButton>
        <ElButton
          type="danger"
          @click="handleDeleteBatch"
          :disabled="isEmpty(checkedIds)"
        >
          批量删除
        </ElButton>
      </template>
    </Grid>
  </Page>
</template>
